package com.alex.keywordtool.pastushov;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.tartarus.snowball.ext.russianStemmer;

import com.alex.keywordtool.Keyword;
import com.alex.keywordtool.KeywordFilter;
import com.alex.keywordtool.KeywordParser;

public class Russian {

	private static KeywordParser parser = new KeywordParser();

	public static void main(String[] args) throws IOException {
		Set<String> searchKeywords = new HashSet<String>(FileUtils.readLines(new File("/home/alex/keywords/раскрутка_сайта.txt")));
		List<SearchKeyword> parsedSearchKeywords = parse(searchKeywords);

		Collection<String> keywords = new LinkedHashSet<String>();
		keywords.addAll(searchKeywords);
		parser.parse("/home/alex/Desktop/russian/Keywords_and_datas.txt", "cp1251", keywords, new Filter(parsedSearchKeywords));
		
		FileUtils.writeLines(new File("/tmp/keywords"), keywords);
	}

	private static List<SearchKeyword> parse(Set<String> searchKeywords) {
		russianStemmer stemmer = new russianStemmer();
		List<SearchKeyword> result = new ArrayList<Russian.SearchKeyword>(searchKeywords.size());
		for (String keyword : searchKeywords) {
			String[] parts = StringUtils.split(keyword, " ");
			for (int i = 0; i < parts.length; i++) {
				stemmer.setCurrent(parts[i]);
				if (stemmer.stem()) {
					parts[i] = stemmer.getCurrent();
				}
			}
			result.add(new SearchKeyword(parts));
		}
		return result;
	}

	private static class SearchKeyword {

		private String[] parts;

		public SearchKeyword(String[] parts) {
			this.parts = parts;
		}

		public String[] getParts() {
			return parts;
		}
	}

	private static class Filter implements KeywordFilter {

		private List<SearchKeyword> searchKeywords;

		public Filter(List<SearchKeyword> searchKeywords) {
			this.searchKeywords = searchKeywords;
		}

		public boolean filter(Keyword keyword) {
			for (SearchKeyword searchKeyword : searchKeywords) {
				boolean flag = true;
				for (String part : searchKeyword.getParts()) {
					if (!keyword.getKeyword().contains(part)) {
						flag = false;
						break;
					}
				}
				if (flag) {
					return true;
				}
			}
			return false;
		}
	}
}
